import { loginApi } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken()
  }
}

const state = getDefaultState()

const mutations = {
  // 1. 存储token
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  // 2. 删除token
  DEL_TOKEN: (state) => {
    state.token = ''
    removeToken()
  }
}

const actions = {
  // 实现登录请求
  async login(context, { username, password }) {
    const res = await loginApi({ username, password })
    // console.log(res.data)
    context.commit('SET_TOKEN', res.data.token)
    Message.success('登录成功')
    router.replace('/')
  },
  // 退出登录
  logout(context) {
    context.commit('DEL_TOKEN')
    router.replace('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

